<template>
  <div class="gauge-dashboard-wrapper" :style="containerStyle">
    <v-chart ref="chartRef" :option="chartOption" :style="chartStyle" autoresize />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { use } from 'echarts/core';
import * as echarts from 'echarts';
import { CanvasRenderer } from 'echarts/renderers';
import { GaugeChart } from 'echarts/charts';
import { TitleComponent, TooltipComponent, LegendComponent } from 'echarts/components';
import VChart from 'vue-echarts';
import { useAutoDataBinding } from '@/composables/use-data-binding';

// 注册ECharts组件
use([CanvasRenderer, GaugeChart, TitleComponent, TooltipComponent, LegendComponent]);

// Props定义
interface Props {
  value?: number;
  name?: string;
  unit?: string;
  dataBinding?: any;
}

const props = withDefaults(defineProps<Props>(), {
  value: 50,
  name: '完成率',
  unit: '%'
});

// 图表引用
const chartRef = ref<InstanceType<typeof VChart>>();

// 响应式属性（用于数据绑定）
const componentProps = computed(() => ({
  value: props.value,
  name: props.name,
  unit: props.unit
}));

// 数据绑定
const shouldUseDataBinding = props.dataBinding?.enabled;
const dataBinding = useAutoDataBinding(
  shouldUseDataBinding ? props.dataBinding : null,
  componentProps
);

// 样式计算
const containerStyle = computed(() => ({
  width: '100%',
  height: '100%',
  minHeight: '400px'
}));

const chartStyle = computed(() => ({
  width: '100%',
  height: '100%'
}));

// 简单仪表盘配置
const chartOption = computed(() => {
  return {
    tooltip: {
      formatter: '{a} <br/>{b} : {c}%'
    },
    series: [
      {
        name: componentProps.value.name,
        type: 'gauge',
        detail: {
          formatter: '{value}' + componentProps.value.unit
        },
        data: [
          {
            value: componentProps.value.value,
            name: componentProps.value.name
          }
        ],
        axisLine: {
          show: true,
          lineStyle: {
            color: [
              [
                1,
                new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                  {
                    offset: 0.1,
                    color: '#FFC600'
                  },
                  {
                    offset: 0.6,
                    color: '#30D27C'
                  },
                  {
                    offset: 1,
                    color: '#0B95FF'
                  }
                ])
              ]
            ]
          }
        }
      }
    ]
  };
});

onMounted(() => {
  // 确保图表可以正确响应尺寸变化
  if (chartRef.value) {
    // 延迟调用resize确保图表正确渲染
    setTimeout(() => {
      chartRef.value?.resize();
    }, 100);
  }
});
</script>

<style scoped>
.gauge-dashboard-wrapper {
  width: 100%;
  height: 100%;
  position: relative;
  overflow: hidden;
  border-radius: 8px;
}

.gauge-dashboard-wrapper > div {
  width: 100% !important;
  height: 100% !important;
}
</style>
